<template>
	<view class="cart-page">
		<!-- 购物车头部 -->
		<view class="cart-header">
			<text class="cart-title">共({{ totalCount }})件</text>
			<text class="cart-edit" @click="toggleEditMode">{{ isEditMode ? '完成' : '编辑' }}</text>
		</view>

		<!-- 购物车内容 -->
		<scroll-view scroll-y class="cart-content" v-if="cartItems.length > 0">
			<!-- 商家列表 -->
			<view class="cart-merchant" v-for="merchant in cartItems" :key="merchant.id">
				<view class="cart-merchant-header">
					<uni-icons :type="merchant.selected ? 'checkbox-filled' : 'circle'" size="20"
						:color="merchant.selected ? '#e4393c' : '#ccc'"
						@click="toggleMerchantSelect(merchant.id)"></uni-icons>
					<text class="cart-merchant-name">{{ merchant.name }}</text>
					<text class="cart-merchant-tag" v-if="merchant.isOfficial">官方</text>
				</view>

				<!-- 商品列表 -->
				<view class="cart-item" v-for="item in merchant.items" :key="item.id">
					<uni-icons :type="item.selected ? 'checkbox-filled' : 'circle'" size="20"
						:color="item.selected ? '#e4393c' : '#ccc'"
						@click="toggleItemSelect(merchant.id, item.id)"></uni-icons>
					<image class="cart-item-image" :src="item.image" mode="aspectFill" />
					<view class="cart-item-info">
						<text class="cart-item-title">{{ item.name }}</text>
						<text class="cart-item-sku">{{ item.sku }}</text>
						<text class="cart-item-price">¥{{ item.price }}</text>
						<view class="cart-item-quantity">
							<text class="quantity-btn-l" @click="changeQuantity(merchant.id, item.id, -1)"
								:class="{ disabled: item.quantity <= 1 }">-</text>
							<input class="quantity-input" type="number" v-model="item.quantity"
								@change="handleQuantityChange(merchant.id, item.id, $event)" />
							<text class="quantity-btn-r" @click="changeQuantity(merchant.id, item.id, 1)">+</text>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 空购物车 -->
		<view class="cart-empty" v-else>
			<uni-icons type="cart" size="60" color="#ddd"></uni-icons>
			<text class="cart-empty-text">购物车还是空的</text>
			<button class="cart-empty-button" @click="goToHome">去逛逛</button>
		</view>

		<!-- 购物车底部 -->
		<view class="cart-footer" v-if="cartItems.length > 0">
			<uni-icons :type="allSelected ? 'checkbox-filled' : 'circle'" size="20"
				:color="allSelected ? '#e4393c' : '#ccc'" @click="toggleAllSelect"></uni-icons>
			<text class="cart-footer-text">全选</text>
			<view class="cart-footer-total">
				合计: <text class="cart-footer-total-price">¥{{ totalPrice.toFixed(2) }}</text>
			</view>
			<button class="cart-footer-checkout" @click="checkout">{{ isEditMode ? '删除' :
				`结算(${selectedCount})` }}</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'

	// 购物车数据
	const cartItems = ref([{
			id: 1,
			name: '名创优品旗舰店',
			isOfficial: true,
			selected: true,
			items: [{
					id: 101,
					name: '便携式蓝牙音箱 无线迷你音响',
					sku: '颜色：蓝色 | 容量：标准版',
					price: 49.9,
					quantity: 1,
					image: 'https://images.unsplash.com/photo-1526170375885-4d8ecf77b99f?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2070&q=80',
					selected: true
				},
				{
					id: 102,
					name: '不锈钢保温杯 真空双层保温水杯',
					sku: '颜色：粉色 | 容量：500ml',
					price: 39.9,
					quantity: 1,
					image: 'https://images.unsplash.com/photo-1607082348824-0a96f2a4b9da?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2070&q=80',
					selected: true
				}
			]
		},
		{
			id: 2,
			name: '名创优品数码专营店',
			isOfficial: false,
			selected: true,
			items: [{
				id: 201,
				name: '时尚太阳镜 防紫外线墨镜',
				sku: '款式：方框 | 颜色：黑色',
				price: 59.9,
				quantity: 1,
				image: 'https://images.unsplash.com/photo-1572635196237-14b3f281503f?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2080&q=80',
				selected: true
			}]
		}
	])

	const isEditMode = ref(false)

	// 计算属性
	const totalCount = computed(() => {
		return cartItems.value.reduce((total, merchant) => {
			return total + merchant.items.length
		}, 0)
	})

	const selectedCount = computed(() => {
		return cartItems.value.reduce((total, merchant) => {
			return total + merchant.items.filter(item => item.selected).length
		}, 0)
	})

	const totalPrice = computed(() => {
		return cartItems.value.reduce((total, merchant) => {
			return total + merchant.items.reduce((sum, item) => {
				return item.selected ? sum + (item.price * item.quantity) : sum
			}, 0)
		}, 0)
	})

	const allSelected = computed(() => {
		return cartItems.value.every(merchant => {
			merchant.selected && merchant.items.every(item => item.selected)
		})
	})

	// 方法
	const toggleEditMode = () => {
		isEditMode.value = !isEditMode.value
	}

	const toggleMerchantSelect = (merchantId) => {
		const merchant = cartItems.value.find(m => m.id === merchantId)
		if (merchant) {
			// 如果要选中当前商家
			if (!merchant.selected) {
				// 先取消其他商家的选中状态
				cartItems.value.forEach(m => {
					if (m.id !== merchantId) {
						m.selected = false
						m.items.forEach(item => item.selected = false)
					}
				})
			}
			merchant.selected = !merchant.selected
			merchant.items.forEach(item => {
				item.selected = merchant.selected
			})
		}
	}

	const toggleItemSelect = (merchantId, itemId) => {
		const merchant = cartItems.value.find(m => m.id === merchantId)
		if (merchant) {
			const item = merchant.items.find(i => i.id === itemId)
			if (item) {
				// 如果要选中商品
				if (!item.selected) {
					// 先取消其他商家的商品选中状态
					cartItems.value.forEach(m => {
						if (m.id !== merchantId) {
							m.selected = false
							m.items.forEach(i => i.selected = false)
						}
					})
					// 给出提示
					if (selectedCount.value > 0) {
						uni.showToast({
							title: '只能选择同一个商家的商品',
							icon: 'none'
						})
					}
				}
				item.selected = !item.selected
				// 检查商家是否应该被全选
				merchant.selected = merchant.items.every(i => i.selected)
			}
		}
	}

	const toggleAllSelect = () => {
		const newStatus = !allSelected.value
		cartItems.value.forEach(merchant => {
			merchant.selected = newStatus
			merchant.items.forEach(item => {
				item.selected = newStatus
			})
		})
	}

	const changeQuantity = (merchantId, itemId, delta) => {
		const merchant = cartItems.value.find(m => m.id === merchantId)
		if (merchant) {
			const item = merchant.items.find(i => i.id === itemId)
			if (item) {
				const newQuantity = item.quantity + delta
				if (newQuantity >= 1 && newQuantity <= 99) {
					item.quantity = newQuantity
				}
			}
		}
	}

	const handleQuantityChange = (merchantId, itemId, e) => {
		let value = parseInt(e.detail.value)
		if (isNaN(value) || value < 1) value = 1
		if (value > 99) value = 99

		const merchant = cartItems.value.find(m => m.id === merchantId)
		if (merchant) {
			const item = merchant.items.find(i => i.id === itemId)
			if (item) {
				item.quantity = value
			}
		}
	}

	const checkout = () => {
		if (isEditMode.value) {
			// 删除选中的商品
			cartItems.value.forEach(merchant => {
				merchant.items = merchant.items.filter(item => !item.selected)
			})
			// 移除空商家
			cartItems.value = cartItems.value.filter(merchant => merchant.items.length > 0)
		} else {
			// 检查是否选择了多个商家的商品
			const selectedMerchants = cartItems.value.filter(merchant =>
				merchant.items.some(item => item.selected)
			)
			
			if (selectedMerchants.length > 1) {
				uni.showToast({
					title: '只能结算同一个商家的商品',
					icon: 'none'
				})
				return
			}
			
			if (selectedCount.value === 0) {
				uni.showToast({
					title: '请选择要结算的商品',
					icon: 'none'
				})
				return
			}

			uni.showToast({
				title: `结算${selectedCount.value}件商品`,
				icon: 'none'
			})
		}
	}

	const goToHome = () => {
		uni.switchTab({
			url: '/pages/index/index'
		})
	}
</script>

<style lang="scss" scoped>
	.cart-page {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f8f8f8;
	}

	.cart-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 15px;
		background-color: #fff;
		border-bottom: 1px solid #eee;

		.cart-title {
			font-size: 16px;
			font-weight: bold;
		}

		.cart-edit {
			font-size: 14px;
			color: #333;
		}
	}

	.cart-content {
		flex: 1;
	}

	.cart-merchant {
		padding: 5px;
		margin: 15px;
		background-color: #fff;
		border-radius: 12px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

		&-header {
			display: flex;
			align-items: center;
			margin-bottom: 10px;
		}

		&-name {
			font-size: 14px;
			font-weight: bold;
			margin-left: 8px;
		}

		&-tag {
			font-size: 11px;
			padding: 1px 5px;
			border-radius: 3px;
			background-color: rgba(228, 57, 60, 0.1);
			color: #e4393c;
			margin-left: 5px;
		}
	}

	.cart-item {
		display: flex;
		padding: 15px 0;
		border-top: 1px solid #eee;

		&-image {
			width: 80px;
			height: 80px;
			border-radius: 5px;
			margin: 0 10px;
		}

		&-info {
			flex: 1;
			display: flex;
			flex-direction: column;
		}

		&-title {
			font-size: 14px;
			margin-bottom: 5px;
			line-height: 1.3;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			overflow: hidden;
		}

		&-sku {
			font-size: 12px;
			color: #999;
			margin-bottom: 5px;
		}

		&-price {
			font-size: 16px;
			color: #e4393c;
			font-weight: bold;
			margin-bottom: 10px;
		}

		&-quantity {
			display: flex;
			align-items: center;
			gap: 8px;

			.quantity-btn-l,
			.quantity-btn-r {
				width: 28px;
				height: 28px;
				border-radius: 6px;
				background-color: #f5f5f5;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 16px;
				color: #333;
				transition: all 0.2s ease;

				&:active {
					background-color: #e0e0e0;
					transform: scale(0.95);
				}

				&.disabled {
					background-color: #f5f5f5;
					color: #ccc;
					cursor: not-allowed;
				}
			}

			.quantity-input {
				width: 40px;
				height: 28px;
				text-align: center;
				border: 1px solid #eee;
				border-radius: 6px;
				font-size: 14px;
				color: #333;
				background-color: #fff;

				&:focus {
					border-color: #e4393c;
					outline: none;
				}
			}
		}
	}

	.cart-empty {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 60vh;

		&-text {
			font-size: 16px;
			color: #999;
			margin: 20px 0;
		}

		&-button {
			padding: 8px 20px;
			background-color: #e4393c;
			color: white;
			border-radius: 20px;
			font-size: 14px;
		}
	}

	.cart-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 50px;
		background-color: #fff;
		display: flex;
		align-items: center;
		padding: 0 15px;
		border-top: 1px solid #eee;

		&-text {
			font-size: 14px;
			margin-left: 8px;
			margin-right: auto;
		}

		&-total {
			font-size: 14px;
			margin-right: 10px;

			&-price {
				color: #e4393c;
				font-weight: bold;
			}
		}

		&-checkout {
			width: 100px;
			height: 36px;
			background-color: #e4393c;
			color: white;
			border-radius: 18px;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 14px;
			margin: 0;
			padding: 0;

			&::after {
				border: none;
			}
		}
	}
</style>